'use strict'

const axios = require('axios')
const qs = require('qs')
const fs = require('fs')
const request = require('request')

const GET = async (url, query) => {
  url += `?${qs.stringify(query)}`
  return new Promise((resolve, reject) => {
    axios
      .get(url)
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * @param  {...any} args 参数
 * (url, data)
 * (url, query, data)
 */
const POST = (...args) => {
  let url = args[0]
  const reqData = args[args.length - 1]

  if (args.length === 3) {
    url += `?${qs.stringify(args[1])}`
  }

  console.log(url, 'urlurlurlurl')
  return new Promise((resolve, reject) => {
    axios
      .post(url, reqData)
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * @param  {...any} args 参数
 * (url, data)
 * (url, query, data)
 */
const UPLOAD = (...args) => {
  let url = args[0]
  const reqData = args[args.length - 1]

  if (args.length === 3) {
    url += `?${qs.stringify(args[1])}`
  }

  return new Promise((resolve, reject) => {
    request.post(
      {
        url,
        headers: { 'content-type': 'multipart/form-data' },
        formData: reqData,
      },
      (err, httpResponse, body) => {
        if (err) reject(err)
        if (
          typeof body === 'string' &&
          body[0] === '{' &&
          body[body.length - 1] === '}'
        ) {
          resolve(JSON.parse(body))
        }
        resolve(body)
      }
    )
  })
}

const API = {}
const apiPath = './'

// api
fs.readdirSync(`${__dirname}/${apiPath}`)
  .filter(value => {
    return value !== 'index.js' && value.indexOf('.js') > -1 // 过滤入口文件
  })
  .map(fileName => {
    API[fileName.split('.js')[0]] = require(`${apiPath}/` + fileName)({
      POST,
      GET,
      UPLOAD,
    })
    return fileName
  })

module.exports = API
